package com.heima.common.util;

import cn.hutool.json.JSONUtil;
import com.aliyun.ocr_api20210707.models.RecognizeAllTextResponse;
import com.aliyun.ocr_api20210707.models.RecognizeBasicResponse;
import com.aliyun.tea.*;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "aliyun")
public class OcrImageUtil {
    private  String accessKeyId;
    private   String accesskeysecret;

    public  com.aliyun.ocr_api20210707.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(accesskeysecret);
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }

    public String getImageText(byte[] image) throws Exception {
        // 使用ByteArrayInputStream将byte[]转换为InputStream
        InputStream inputStream = new ByteArrayInputStream(image);
        com.aliyun.ocr_api20210707.Client client = createClient();
        com.aliyun.ocr_api20210707.models.RecognizeBasicRequest recognizeBasicRequest = new com.aliyun.ocr_api20210707.models.RecognizeBasicRequest()
                .setBody(inputStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeBasicResponse res = client.recognizeBasicWithOptions(recognizeBasicRequest, runtime);
            if (res.getStatusCode() == 200) {
                String data = res.getBody().getData();
                String content = (String) JSONUtil.toBean(data, Map.class).get("content");
                return content;
            }

            System.out.println(res);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }
}